import random from '../utils/random.js'

Component({
  properties: {
    speed: {
      type: Number,
      value: 50
    },
    width: {
      type: Number,
      value: 375
    },
    height: {
      type: Number,
      value: 500
    },
    text: {
      type: String,
      value: ''
    },
    headpicpath: {
      type: String,
      value: ''
    },
    picPath: {
      type: String,
      value: ''
    },
  },
  data: {
    position: {
      x: 0,
      y: 0,
    },
    duration: 0,
  },
  methods: {
    /**
     * 计算运动距离
     */
    calcDistance(x, y) {
      const disX = Math.abs(x - this.data.position.x)
      const disY = Math.abs(y - this.data.position.y)

      return Math.sqrt(disX * disX + disY * disY)
    },

    /**
     * 计算运动时间
     */
    calcDuration(distance){
      let duration = distance / this.data.speed
      if (duration < this.MINTIME) {
        duration = this.MINTIME
      }
      return duration
    },

    /**
     * 随机X,Y坐标
     */
    randomAxis(){
      return {
        x: random(0, this.data.width),
        y: random(0, this.data.height)
      }
    },

    /**
     * 初始化位置
     */
    initPosition(){
      const { x, y } = this.randomAxis()

      const distance = this.calcDistance(x, y)
      const duration = this.calcDuration(distance)
      this.setData({
        position: {
          x,
          y
        },
        duration: 0,
      }, () => {
        // 初始化位置之后开始第一次动画
        this.randomPosition()
      })
    },

    /**
     * 随机位置
     */
    randomPosition(){
      if (this.RUNNING) return

      this.RUNNING = true

      const { x, y } = this.randomAxis()

      const distance = this.calcDistance(x, y)
      const duration = this.calcDuration(distance)

      this.setData({
        position: {
          x,
          y,
        },
        duration,
      }, () => {
        setTimeout(() => {
          this.RUNNING = false
        }, this.MINTIME * 1000)
      })
    },

    /**
     * transitionend事件监听
     */
    onTransitionEnd(){
      this.randomPosition()
    },

    /**
     * 气泡点击事件
     */
    onItemClick(evt){
      console.log('evt',evt)
      const { text } = evt.target.dataset
      var myEventDetail = { text } // detail对象，提供给事件监听函数
      var myEventOption = {} // 触发事件的选项
      this.triggerEvent('onItemClick', myEventDetail, myEventOption)
    }
  },
  created(){
    this.RUNNING = false  // 防止重复设置新位置
    this.MINTIME = 1 // 最小运动时间
  },
  ready(){
    this.initPosition() //初始化气泡位置
  }
})
